package com.ry.jwtexp.jwt.interceptor;

import com.ry.jwtexp.jwt.TokenUtils;
import com.ry.jwtexp.jwt.annonation.IgnoreToken;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author ry
 * @Description
 * @Date 2020/9/1 9:36
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行options请求
        if (request.getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }

        //获取方法上的注解是否忽略 token认证
        Method method = null;
        if (handler instanceof HandlerMethod) {
            method = ((HandlerMethod) handler).getMethod();
            IgnoreToken annotation = method.getAnnotation(IgnoreToken.class);
            //方法上没加注解再检查类上面有没有注解
            if (annotation == null) {
                annotation = method.getDeclaringClass().getAnnotation(IgnoreToken.class);
                if(annotation != null){
                    //跳过后面的验证
                    return true;
                }
            }else{
                //跳过后面的验证
                return true;
            }
        }


        //获取token
        String access_token = request.getParameter("access_token");
        if (access_token == null || access_token.trim().isEmpty()) {
            access_token = request.getHeader("Authorization");
            if (access_token == null && access_token.trim().isEmpty()){
                throw new Exception("token不能为空");
            }
        }

        //校验token
        String validAccount = TokenUtils.validToken(access_token);
        if(!StringUtils.isEmpty(validAccount)){
            //校验成功
            return true;
        }


        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
